package com.ghn.cocknovel.ui.activity.map


import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.example.basemodel.base.BaseActivity
import com.example.basemodel.utils.NotificationUtils
import com.example.basemodel.utils.StatusBarUtils
import com.ghn.cocknovel.BR
import com.ghn.cocknovel.R
import com.ghn.cocknovel.constants.Constants
import com.ghn.cocknovel.databinding.ActivityMapBinding
import com.ghn.cocknovel.ext.GONE
import com.ghn.cocknovel.ext.MappageLoadBase
import com.ghn.cocknovel.ext.VISIBLE
import com.ghn.cocknovel.ui.activity.map.vm.MapViewModel
import com.ghn.cocknovel.ui.activity.work.vm.ToDayWorkTaskViewModel
import com.ghn.cocknovel.utils.MapUtils
import com.ghn.cocknovel.view.DialogClickListener
import com.ghn.cocknovel.view.DialogMessage
import com.google.gson.Gson
import com.hjq.permissions.PermissionFragment.launch
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kt.NetworkModel.App
import com.kt.NetworkModel.bean.BQueryDriverTransitOrderListBean
import com.kt.NetworkModel.bean.QueryPassengerBySiteBean
import com.kt.NetworkModel.bean.QueryTransitRouteBean
import com.kt.NetworkModel.utils.MLog
import com.tencent.map.fusionlocation.model.TencentGeoLocation
import com.tencent.map.geolocation.TencentLocationUtils
import com.tencent.navix.api.NavigatorZygote
import com.tencent.navix.api.config.MapAutoScaleConfig
import com.tencent.navix.api.layer.NavigatorLayerRootDrive
import com.tencent.navix.api.location.GeoLocationObserver
import com.tencent.navix.api.location.LocationApi
import com.tencent.navix.api.model.*
import com.tencent.navix.api.model.NavRerouteReqParam.DestinationParamBuilder
import com.tencent.navix.api.navigator.NavigatorDrive
import com.tencent.navix.api.observer.NavigatorDriveObserver
import com.tencent.navix.api.plan.DriveRoutePlanRequestCallback
import com.tencent.navix.api.plan.RoutePlanRequester
import com.tencent.navix.tts.DefaultTTSPlayer
import com.tencent.navix.tts.api.TTSPlayer
import com.tencent.navix.ui.NavigatorLayerViewDrive
import com.tencent.navix.ui.api.config.UIComponentConfig
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory
import com.tencent.tencentmap.mapsdk.maps.TencentMap
import com.tencent.tencentmap.mapsdk.maps.UiSettings
import com.tencent.tencentmap.mapsdk.maps.model.*
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_map.view.*
import kotlinx.android.synthetic.main.mappopitem.view.*
import java.util.*
import java.util.concurrent.TimeUnit


class MapActivity : BaseActivity<ActivityMapBinding, MapViewModel>() {
    protected lateinit var navigatorDrive: NavigatorDrive
    protected var tencentMap: TencentMap? = null
    protected var locationApi: LocationApi? = null
    protected var mCustomMarker: Marker? = null
    protected var mCustomMarkers: Marker? = null
    protected var latLngs = mutableListOf<LatLng>()
    protected var PolylatLngs = mutableListOf<LatLng>()
    protected var sumlat: Double = 0.0
    protected var sumlog: Double = 0.0
    var isOneLocationOk = false //第一次是否定位成功记录
    var mTaskid = ""
    var mSiteId = ""//站点ID
    var mLastSiteState = -1//站点ID
    var siteLongitude = 0.0
    var siteLatitude = 0.0
    lateinit var mQueryTransitOrderDisposable: Disposable
    lateinit var mQueryTransitNotificationDisposable: Disposable
    var layerViewDrive: NavigatorLayerViewDrive? = null
    var layerRootDrive: NavigatorLayerRootDrive? = null

    var isBottomUI = true//是否显示底部的ui
    var isTextView = true//控制多次重复点击
    val mWorkAdapter by lazy { MapPopAdapter() }
    val mNextAdapter by lazy { NextAdapter() }
    var mFenceAreaId = ""
    var isStartNavigationMap = false//是否开启导航

    val mToDayWorkTaskViewModel by lazy { ToDayWorkTaskViewModel(App.get()) }

    val dayOfWeek = arrayOf("周日", "周一", "周二", "周三", "周四", "周五", "周六")

    val mCarNavigatorDriveObserver by lazy { CarNavigatorDriveObserver() }
    override fun initVariableId(): Int {
        return BR.mode
    }

    override fun initContentView(savedInstanceState: Bundle?): Int = R.layout.activity_map

    override fun initParam() {
        mTaskid = if (intent.getStringExtra("taskId") == null) "" else intent.getStringExtra("taskId").toString()
        mFenceAreaId = intent.getStringExtra("fenceAreaId").toString()
        //设置返回按钮位置
        StatusBarUtils.setBackMarginTop(this, binding.btnBack)

        binding.mapview.isOpaque = false
        //创建tencentMap地图对象，可以完成对地图的几乎所有操作
        tencentMap = binding.mapview.map
        //获取UiSettings实例
        val uiSettings: UiSettings = binding.mapview.map.uiSettings
        uiSettings.isZoomGesturesEnabled = true


        // 创建驾车 NavigatorDrive
        navigatorDrive = NavigatorZygote.with(this).navigator(
            NavigatorDrive::class.java
        )


        locationApi = navigatorDrive.locationApi()
        navigatorDrive.registerObserver(mCarNavigatorDriveObserver)


        // 注册定位回调
        locationApi?.addLocationObserver(locationObserver, 3000)

        mNextAdapter.bindToRecyclerView(binding.nextList)
        binding.navigatorViewStub.setTravelMode(NavRouteReqParam.TravelMode.TravelModeDriving)
        binding.navigatorViewStub.inflate()
        layerRootDrive = binding.navigatorViewStub.getNavigatorView<NavigatorLayerRootDrive>()
        // 创建默认面板 NavigatorLayerViewDrive，并添加到导航地图层
        layerViewDrive = NavigatorLayerViewDrive(this)
        layerRootDrive?.addViewLayer(layerViewDrive)
        // 将导航地图层绑定到Navigator
        navigatorDrive.bindView(layerRootDrive)
        //设置途经点判达策略 Automatically 	导航内自动判达     Manually 	外部手动
        navigatorDrive.setWaypointArriveMode(NavWaypointArriveMode.Manually)
        //注册回调

        layerViewDrive!!.setUIComponentConfig(
            UIComponentConfig.builder().setAllComponentVisibility(true).setComponentVisibility(UIComponentConfig.UIComponent.ZOOM_CONTROLLER_VIEW, true)
                .setComponentVisibility(UIComponentConfig.UIComponent.ENLARGE_INFO_VIEW, false)


                .setComponentVisibility(UIComponentConfig.UIComponent.GUIDE_LANE_VIEW, false).setComponentVisibility(UIComponentConfig.UIComponent.MAP_TRAFFIC_SWITCH_VIEW, false)

                .setComponentVisibility(UIComponentConfig.UIComponent.REROUTE_SWITCH_VIEW, false).setComponentVisibility(UIComponentConfig.UIComponent.ROAD_TYPE_SWITCH_VIEW, false)


                .setComponentVisibility(UIComponentConfig.UIComponent.ROUTE_EXPLAIN_VIEW, false).setComponentVisibility(UIComponentConfig.UIComponent.TRAFFIC_BAR_VIEW, false)
                .setComponentVisibility(UIComponentConfig.UIComponent.INFO_VIEW, false).build()
        )


        layerRootDrive?.setAutoScaleConfig(MapAutoScaleConfig(false, 1000f))
        //导航添加语音提示
        navigatorDrive.ttsPlayer = DefaultTTSPlayer()


        //导航
        binding.mapTvNavigation.setOnClickListener {
            startActivity(Intent(this, NavigatActivity::class.java))
        }
        //查看详情
        binding.mapCenten.setOnClickListener {
            startActivity(
                Intent(this, MapCentenActivity::class.java).putExtra("taskId", mTaskid).putExtra("siteId", mSiteId).putExtra("mapJump", true)//下级页面显示底部按钮
            )
        }
        //点击底部按钮出弹窗
        binding.mapReach.setOnClickListener {
            showLoading()
            // 根据对应状态  调用接口
            when (viewModel.queryPassengerBySite.value?.siteState) {
                1 -> {
                    viewModel.transitArriveStartingPoint(mSiteId.toInt(), siteLatitude.toString(), siteLongitude.toString())
                }

                2 -> {
                    viewModel.updateDriverNextSite(mSiteId, siteLatitude.toString(), siteLongitude.toString())
                }
            }
        }
        binding.btnBackCart.setOnClickListener {
            // 结束任务
//            mToDayWorkTaskViewModel.finishTransitSchedulePlanNet(mTaskid, siteLongitude, siteLatitude)
            finish()
        }
        binding.btnBack.setOnClickListener {
            finish()
        }

        binding.btnStopOrder.setOnClickListener {
            binding.btnStopOrder.tag?.also {
                when (it) {
                    "点击正常接单" -> {
                        binding.btnStopOrder.isClickable = false
                        showLoading()
                        //正常接单
                        viewModel.updateDiverReceiveOrderNet(1)
                    }

                    "点击暂停接单" -> {
                        DialogMessage(this).setMessageTitle("提示").setContext("暂停派单后系统将不会向您派送订单").setYesText("确定暂停派单").setClickListener(object : DialogClickListener() {
                            override fun yesClick(dailog: Dialog?) {
                                // 暂停派单 1正常接单【如果司机此刻是暂停派单状态显示】 2暂停接单【如果司机此刻是正常接单状态显示】
                                binding.btnStopOrder.isClickable = false
                                showLoading()
                                viewModel.updateDiverReceiveOrderNet(2)
                            }

                        }).show()
                    }
                }
            }
        }
        binding.btnStopOrder2.setOnClickListener {
            binding.btnStopOrder2.tag?.also {
                when (it) {
                    "点击正常接单" -> {
                        binding.btnStopOrder.isClickable = false
                        showLoading()
                        //正常接单
                        viewModel.updateDiverReceiveOrderNet(1)
                    }

                    "点击暂停接单" -> {
                        DialogMessage(this).setMessageTitle("提示").setContext("暂停派单后系统将不会向您派送订单").setYesText("确定暂停派单").setClickListener(object : DialogClickListener() {
                            override fun yesClick(dailog: Dialog?) {
                                // 暂停派单 1正常接单【如果司机此刻是暂停派单状态显示】 2暂停接单【如果司机此刻是正常接单状态显示】
                                binding.btnStopOrder.isClickable = false
                                showLoading()
                                viewModel.updateDiverReceiveOrderNet(2)
                            }

                        }).show()
                    }
                }
            }
        }
        viewModel.mUpdateDiverReceiveOrderLiveData.observe(this) {
            dismissLoading()
            binding.btnStopOrder2.isClickable = true
            binding.btnStopOrder.isClickable = true

            if (binding.btnStopOrder.tag == "点击正常接单") {
                binding.btnStopOrder.text = "点击暂停接单"
                binding.btnStopOrder.tag = "点击暂停接单"
            } else {
                binding.btnStopOrder.text = "点击正常接单"
                binding.btnStopOrder.tag = "点击正常接单"
            }

            if (binding.btnStopOrder2.tag == "点击正常接单") {
                binding.btnStopOrder2.text = "点击暂停接单"
                binding.btnStopOrder2.tag = "点击暂停接单"
            } else {
                binding.btnStopOrder2.text = "点击正常接单"
                binding.btnStopOrder2.tag = "点击正常接单"
            }

            //当前状态更新
//            showMsg(if (it == 1) "暂停成功" else "开始接单")
        }
        mQueryTransitOrderDisposable = Observable.interval(2, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({
            //任务详情页查询任务信息
            viewModel.queryTransitOrder()


        }) {}

        mQueryTransitNotificationDisposable = Observable.interval(10, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({
            viewModel.queryPassengerBySite.value?.also {
                //查询司机提示语【司机点弹窗触发后台关闭弹窗接口 后台设置关闭】【需要定时任务定时查询】
                //正常接单查询提示
                if (it.canReceiveOrder == 1) {
                    viewModel.queryTransitPromptNet()
                }
            }

        }) {}


        //查询区域坐标集合
        viewModel.queryTransitFenceAreaCoordinate(mFenceAreaId)
        createObserver()
        binding.tvOverShowTime.setOnClickListener {

        }
    }

    var isShowDailog = false
    var isPlayText = true //到站提醒
    private val lock = Any()
    fun createObserver() {
        viewModel.queryPassengerBySite.observe(this@MapActivity) {
            synchronized(lock) {
                updateView(it)
            }
        }
        mToDayWorkTaskViewModel.mOverSubmitLiveData.observe(this) {
            finish()
        }
        viewModel.onTransit.observe(this) {
            //确认订单后 刷新列表
            viewModel.squeryDriverTransitOrderList(viewModel.queryPassengerBySite.value?.siteId.toString(), 1, mTaskid)
        }
        viewModel.queryTransitRouteBeanLiveData.observe(this) {
            //查询后续站点
            mNextAdapter.setNewData(it)
        }
        viewModel.mQueryTransitPromptBeanLiveData.observe(this) {
            NotificationUtils.showNotification(this, "", it.promptDesc)
            //关闭弹窗提示
            viewModel.updateTransitPromptNet()
        }
        viewModel.queryDriverTransitOrderList.observe(this) {
            dismissLoading()
            MappageLoadBase(it, mWorkAdapter)
        }
        viewModel.updateDriverNextSite.observe(this) {
//                    Log.i("TAG", "initPopWindow: $")
//            if (it.equals("当前站点存在需要操作的订单,请确认完成后继续行程")) {
//                isBottomUI = false//是否显示底部的ui
//                binding.mapTvNavigation.visibility = View.GONE
//                binding.llyBottom.visibility = View.GONE
//                binding.mapReach.visibility = View.GONE
//            }
            dismissLoading()
            isBottomUI = true//是否显示底部的ui
            isTextView = false
//            mPopwindow?.dismiss()
            viewModel.queryTransitOrder()
        }
        viewModel.updateDriverNextSiteError.observe(this) {
            dismissLoading()
            startActivity(
                Intent(this, MapCentenActivity::class.java).putExtra("taskId", mTaskid).putExtra("siteId", mSiteId).putExtra("mapJump", true)//下级页面显示底部按钮
            )
        }
        viewModel.transitArriveStartingPointError.observe(this) {
            dismissLoading()
            if (it == 2) {
                startActivity(
                    Intent(this, MapCentenActivity::class.java).putExtra("taskId", mTaskid).putExtra("siteId", mSiteId).putExtra("mapJump", true)//下级页面显示底部按钮
                )
            }
        }
        viewModel.transitArriveStartingPoint.observe(this) {
            dismissLoading()
            if (it.equals("1") || it.equals("2")) {
                isBottomUI = false
//                    initPopWindow()
//                mPopwindow?.showAtLocation(binding.mapview, Gravity.CENTER, 0, 0)
            }
            //司机到达站点停止导航
//            stopNavigationMap()
            viewModel.queryTransitOrder()
            //到达下个页面
            startActivity(
                Intent(this, MapCentenActivity::class.java).putExtra("taskId", mTaskid).putExtra("siteId", mSiteId).putExtra("mapJump", true)//下级页面显示底部按钮
            )
        }
        viewModel.queryTransitFenceAreaCoordinate.observe(this@MapActivity) {
            val mapOptions = PolygonOptions().fillColor(Color.argb(80, 162, 200, 239)).strokeWidth(5f)
            it?.forEach { a ->
                latLngs.add(LatLng(a.lat, a.lng))
                sumlat += a.lat
                sumlog += a.lng
            }
            if (mapOptions.points == null || mapOptions.points.isEmpty()) {
                mapOptions.strokeColor(getColor(R.color.color_base_blue))
                mapOptions.add(latLngs)
                tencentMap?.addPolygon(mapOptions)
            }
            val polylineOptions = PolylineOptions().addAll(PolylatLngs) // 折线设置圆形线头
                // 折线设置圆形线头
                .lineCap(true)
                // 折线的颜色为绿色
                .color(R.color.blue1)
                // 折线宽度为25像素
                .width(10F)
            tencentMap?.addPolyline(polylineOptions)
        }



        LiveEventBus.get<String>("driverNextSite").observe(this) {
            MLog.d("------driverNextSite----》  收到通知")
            //通知关闭弹窗
//            mPopwindow!!.dismiss()
            isBottomUI = true//是否显示底部的ui
            binding.llyBottom.visibility = View.VISIBLE
            binding.mapReach.visibility = View.VISIBLE


            // 展示导航模块
//            startNavigationMap()
        }
//        viewModel.queryOverTimeLiveData.observe(this) {
//            Handler(Looper.getMainLooper()).postDelayed({
//                if (isFinishing) return@postDelayed
//                DialogMessage(this).setContext("已等待${it / 1000}秒”").setMessageContentColor(Color.RED).show()
//            }, it)
//        }
//        LiveEventBus.get<String>(Constants.EventBus.DRIVER_TO_SITE).observe(this) {
//            //查询站点倒计时
//            viewModel.queryPassengerBySite.value?.also {
//                viewModel.getSiteCountdown(it.siteId)
//            }
//
//        }
//        viewModel.queryPassengerBySite.observe(this@MapActivity) {
//            if (item?.OnTransit == true) {
//                Log.i(BaseQuickAdapter.TAG, "convert:${item.OnTransit}")
//
//                item.OnTransit = false
//            }
//
//        }
    }


    private fun updateView(it: QueryPassengerBySiteBean?) {

        binding.mapTvAddress.text = ">>  " + it?.siteName
//            showMsg(Gson().toJson(it))
        it?.also {
            if (MapUtils.isGoToEnd(it.siteLatitude, it.siteLongitude, siteLatitude, siteLongitude)) {
                if (isPlayText) {
                    isPlayText = false
                    if (!TextUtils.isEmpty(it.siteName)) {
                        navigatorDrive.ttsPlayer.broadcast(NavTTSInfo(NavTTSInfo.BeepType.None.asValue(), "${it.siteName}车站到了”"))
                    }
                }
            } else {
                isPlayText = true
            }
        }

//            binding.mapTvAddress.text = if (TextUtils.isEmpty(it?.nextSiteName.toString())) it?.siteName else it?.nextSiteName
        //判断当前是否路线变更 站点不同
//            if (binding.mapTvAddress.text.toString().isNotEmpty() && !binding.mapTvAddress.text.equals(it?.siteName)) {
//
//            }
        binding.mapTvUpNumber.text = it?.waitBoardingAdultNum.toString() + "人"
        binding.mapTvUnderNumber.text = it?.boardingAdultNum.toString() + "人"
        binding.mapTvInNumber.text = it?.boardingNum.toString() + "人"
        binding.mapTvRemaining.text = it?.remainingSeats.toString() + "位"
        Log.i("TAG", "createObserver: ${it?.siteState}")
        //1显示到达站点 2显示继续行程3暂无行程
        when (it?.siteState) {
            1 -> {
//                    binding.tvMapTvAddress.text = "正在前往: "
                binding.mapReach.text = "到达" + it.siteName + " 站"
//                    if (mPopwindow != null) {
//                        mPopwindow!!.dismiss()
//                    }
                binding.mapReach.VISIBLE()
                //进行中开启导航
                startNavigationMap()
            }

            2 -> {
                if (it.nextSiteName != null && !TextUtils.isEmpty(it.nextSiteName)) {
                    binding.mapReach.text = "前往下一站:" + it.nextSiteName + " 站"
                } else {
                    binding.mapReach.text = "继续行程"

                }
                binding.mapEmpty.visibility = View.VISIBLE
                binding.llyBottom.visibility = View.VISIBLE
                binding.mapReach.VISIBLE()
                startNavigationMap()
            }

            3 -> {
                binding.mapReach.text = "暂无行程"
                binding.mapEmpty.VISIBLE()
                binding.llyBottom.visibility = View.GONE
                val calendar = Calendar.getInstance()
                val year = calendar.get(Calendar.YEAR)
                //月
                val month = calendar.get(Calendar.MONTH) + 1
                //日
                val day = calendar.get(Calendar.DAY_OF_MONTH)
                val DAY_OF_WEEK = calendar.get(Calendar.DAY_OF_WEEK)
                val week = dayOfWeek[DAY_OF_WEEK - 1]
                val HOUR_OF_DAY = calendar.get(Calendar.HOUR_OF_DAY)
                val MINUTE = calendar.get(Calendar.MINUTE)
                binding.tvOverShowTime.text = "" + year + "年" + month + "月" + day + "日" + " " + week + " " + HOUR_OF_DAY + "：" + MINUTE
                stopNavigationMap()
            }
        }
        when (it?.clickState) {
            1 -> {
                binding.mapReach.isClickable = true
                binding.mapReach.isFocusable = true
                binding.mapReach.solid = getColor(R.color.blue2)
            }

            2 -> {
                binding.mapReach.isClickable = false
                binding.mapReach.isFocusable = false
                binding.mapReach.solid = getColor(R.color.gray8)
                binding.mapReach.setTextColor(getColor(R.color.white))
            }
        }
        //司机当前接单状态 1正常接单 2暂停接单 3司机任务关闭 按钮可以都不用显示了
        when (it?.canReceiveOrder) {
            1 -> {
                //查询后续车次信息
                if (binding.btnStopOrder.tag == null) {
                    binding.btnStopOrder.VISIBLE()
                    binding.btnStopOrder.text = "点击暂停接单"
                    binding.btnStopOrder.tag = "点击暂停接单"
                }

                if (binding.btnStopOrder2.tag == null) {
                    binding.btnStopOrder2.VISIBLE()
                    binding.btnStopOrder2.text = "点击暂停接单"
                    binding.btnStopOrder2.tag = "点击暂停接单"
                }
            }

            2 -> {
                //查询后续车次信息
                if (binding.btnStopOrder.tag == null) {
                    binding.btnStopOrder.VISIBLE()
                    binding.btnStopOrder.text = "点击正常接单"
                    binding.btnStopOrder.tag = "点击正常接单"
                }


                if (binding.btnStopOrder2.tag == null) {
                    binding.btnStopOrder2.VISIBLE()
                    binding.btnStopOrder2.text = "点击正常接单"
                    binding.btnStopOrder2.tag = "点击正常接单"
                }
            }

            3 -> {
                binding.btnStopOrder.GONE()
                binding.btnStopOrder2.GONE()
                binding.btnStopOrder2.tag = null;
                binding.btnStopOrder.tag = null;
            }
        }
        if (it?.siteId == null) {
            binding.mapEmpty.visibility = View.VISIBLE
            binding.llyBottom.visibility = View.GONE
            binding.mapTvNavigation.visibility = View.GONE
        } else {
            MLog.d("isShowDailog---> " + isShowDailog + "      mLastSiteState  " + mLastSiteState + "   siteState  " + it.siteState)
            //第一次不弹窗，  站点ID比对
            if (isShowDailog && mLastSiteState == 3 && it.siteState == 1) {
                DialogOrder()
            }
            binding.mapEmpty.visibility = View.GONE
            if (isBottomUI && it.siteState != 2) {
                binding.llyBottom.visibility = View.VISIBLE
//                    binding.mapTvNavigation.visibility = View.VISIBLE
            }
        }
        if (PolylineOptions == 0 && siteLatitude != 0.0 && siteLongitude != 0.0 && it?.siteLongitude != 0.0 && it?.siteLatitude != 0.0) {
            //当前定位的经纬度
            PolylatLngs.add(LatLng(siteLatitude, siteLongitude))
            PolylatLngs.add(LatLng(it?.siteLatitude!!, it.siteLongitude))
            PolylineOptions++
        }
        //上次的站点ID
        mSiteId = it?.siteId.toString()
        //上次状态
        mLastSiteState = it?.siteState!!
        if (it.siteLatitude != 0.0 && it.siteLongitude != 0.0) {
            if (mCustomMarkers == null) {
                val custom = BitmapDescriptorFactory.fromResource(R.mipmap.over)
                mCustomMarkers = tencentMap?.addMarker(
                    MarkerOptions(LatLng(it.siteLatitude, it.siteLongitude)).icon(custom).alpha(0.7f).flat(false).clockwise(true)
                )
            }

            val translateAnimation = TranslateAnimation(LatLng(it?.siteLatitude!!, it.siteLongitude))
            translateAnimation.duration = 1000
            translateAnimation.interpolator = AccelerateDecelerateInterpolator()
            mCustomMarker?.setAnimation(translateAnimation)
        }
    }


    override fun onStart() {
        super.onStart()
        layerRootDrive?.onStart()
    }

    override fun onRestart() {
        super.onRestart()
        layerRootDrive?.onRestart()
    }

    override fun onResume() {
        super.onResume()
        layerRootDrive?.onResume()
    }

    override fun onPause() {
        super.onPause()
        layerRootDrive?.onPause()
    }

    override fun onStop() {
        super.onStop()
        layerRootDrive?.onStop()
    }


//    var lastNavigatorDriveSiteLatitude = 0.0 //修改导航终点使用
//    var lastNavigatorDriveSiteLongitude = 0.0 //修改导航终点使用

    var mapSiteName = ""

    /**
     * 开始导航
     */
    private fun startNavigationMap() {
        try {
            binding.navigatorViewStub.VISIBLE()
            binding.mapview.GONE()
            if (siteLatitude == 0.0) return
            //判断2点之间距离近 停止导航 //两个点以经纬度的形式计算距离
//            val mBySite = viewModel.queryPassengerBySite.value
//            val distanceBetween = TencentLocationUtils.distanceBetween(siteLatitude, siteLongitude, mBySite!!.siteLatitude, mBySite.siteLongitude)
//            //两点之间距离 小于20米 停止导航
//            if (distanceBetween < 20) {
//                //停止导航
//                stopNavigationMap()
//            }
            isStartNavigationMap = true
            //导航已经开始修改终点坐标
            if (navigatorDrive.isNavigating) {
                viewModel.queryPassengerBySite.value?.also {
//                    MLog.d("isNavigating     ${navigatorDrive.isNavigating}  " + Gson().toJson(viewModel.queryPassengerBySite.value))
                    //如果两次终点坐标不一样修改终点坐标   38.513570,106.259412
                    if (mapSiteName != it.siteName) {
                        MLog.d("isNavigating     新的坐标地点      siteLatitude    ${it.siteLatitude}    siteLongitude   ${it.siteLongitude}")
                        //修改下一站计算
                        navigatorDrive.reroute(
                            NavRerouteReqParam.newBuilder(
                                DestinationParamBuilder::class.java
                            ).dest(NavSearchPoint(it.siteLatitude, it.siteLongitude)).build()
                        )
                    } else {
//                        showMsg("两次导航位置相同==>  " + lastNavigatorDriveSiteLatitude + "    " + lastNavigatorDriveSiteLongitude)
                        MLog.d("isNavigating     两次导航位置相同      siteLatitude    $siteLatitude    siteLongitude   $siteLongitude")

                    }
                    mapSiteName = it.siteName
                    //修正计算运行中的导航
//                    lastNavigatorDriveSiteLatitude = it.siteLatitude
//                    lastNavigatorDriveSiteLongitude = it.siteLongitude
//                    if (testNum==10){
//                        lastNavigatorDriveSiteLatitude=38.513570
//                        lastNavigatorDriveSiteLongitude=106.259412
//                    }
//                    if (testNum==20){
//                        lastNavigatorDriveSiteLatitude=38.515291
//                        lastNavigatorDriveSiteLongitude=106.257191
//                        testNum=0
//                    }
//                    testNum++
//                    showMsg("testNum  "+testNum)

                }

            } else {

                //导航未开始  去导航
                viewModel.queryPassengerBySite.value?.also {
//                    MLog.d("isNavigating     ${navigatorDrive.isNavigating}  " + Gson().toJson(viewModel.queryPassengerBySite.value))
                    if (mapSiteName == it.siteName) {
                        MLog.d("开始导航终点位置相同不在导航")
                        MLog.d("isNavigating     开始导航终点位置相同不在导航     ")
                        return
                    }
                    binding.navigatorViewStub.setTravelMode(NavRouteReqParam.TravelMode.TravelModeDriving)
                    isStartNavigationMap = false
                    //设置途径点
                    val mNavSearchPointList = ArrayList<NavSearchPoint>()
                    // 算路并开启导航
                    navigatorDrive.searchRoute(RoutePlanRequester.Companion.newBuilder(NavRouteReqParam.TravelMode.TravelModeDriving).start(NavSearchPoint(siteLatitude, siteLongitude))
                        //设置途径点
                        .wayPoints(mNavSearchPointList).end(NavSearchPoint(it.siteLatitude, it.siteLongitude)).build(),
                        DriveRoutePlanRequestCallback { navRoutePlan: NavRoutePlan<NavDriveRoute>?, error: NavError? ->
                            if (error != null) {
                                // handle error
                                return@DriveRoutePlanRequestCallback
                            }
                            if (navRoutePlan != null) {
                                val routePlanList = navRoutePlan.routeDatas
                                if (routePlanList != null && routePlanList.size > 0) {
                                    navigatorDrive.startNavigation(navRoutePlan.routeDatas[0].getRouteId())
                                    MLog.d("isNavigating     ${navigatorDrive.isNavigating}  刷新    " + navRoutePlan.routeDatas[0].getRouteId())

                                }
                            }
                        })
                    mapSiteName = it.siteName
                }
            }


            if (layerViewDrive == null) {
                //导航模块设置 start
//                binding.navigatorViewStub.setTravelMode(NavRouteReqParam.TravelMode.TravelModeDriving)
//                binding.navigatorViewStub.inflate()
//                layerRootDrive = binding.navigatorViewStub.getNavigatorView<NavigatorLayerRootDrive>()
//                // 创建默认面板 NavigatorLayerViewDrive，并添加到导航地图层
//                layerViewDrive = NavigatorLayerViewDrive(this)
//                layerRootDrive?.addViewLayer(layerViewDrive)
//
//                // 将导航地图层绑定到Navigator
//                navigatorDrive.bindView(layerRootDrive)


//                layerViewDrive!!.setUIComponentConfig(
//                    UIComponentConfig.builder()
//                    .setAllComponentVisibility(true)
//                        .setComponentVisibility(UIComponentConfig.UIComponent.ZOOM_CONTROLLER_VIEW,false)
//                        .setComponentVisibility(UIComponentConfig.UIComponent.ENLARGE_INFO_VIEW,true)
//                    .build()
//
//                )
//                layerRootDrive?.setAutoScaleConfig(MapAutoScaleConfig(true,15f))
//                layerViewDrive!!.setEnlargedMapUIConfig(EnlargedMapUIConfig.Builder(EnlargedMapUIConfig.builder()
//
//                    .build()).build())


                //导航模块设置 end
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        binding.btnBack.GONE()
    }

    /**
     * 结束导航
     */
    private fun stopNavigationMap() {
        try {
            MLog.d(" isNavigating    stopNavigationMap  ")
            isStartNavigationMap = false
            binding.btnBack.VISIBLE()
            //导航模块展示情况隐藏 解绑
            binding.navigatorViewStub.GONE()
            binding.mapview.VISIBLE()
            navigatorDrive.stopNavigation()
            //  删除地图上存在的位置
            mCustomMarkers?.remove()
            mCustomMarkers = null
            //显示标题返回按钮
//        }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    var gps = 0
    var PolylineOptions = 0
    var locationObserver: GeoLocationObserver = object : GeoLocationObserver() {
        @SuppressLint("SuspiciousIndentation")
        override fun onGeoLocationChanged(tencentGeoLocation: TencentGeoLocation?) {
            super.onGeoLocationChanged(tencentGeoLocation)
            mCustomMarker?.remove()
            //当前状态是否需要导航 导航中不用再次导航   进行中才导航  导航切换       //1显示到达站点 2显示继续行程3暂无行程
            if (isStartNavigationMap) {
//            if (!navigatorDrive.isNavigating&&viewModel.queryPassengerBySite.value?.siteState==1) {


            }
            if (tencentGeoLocation?.location?.latitude == null) return
            if (gps == 0) {
                val cameraSigma = CameraUpdateFactory.newCameraPosition(
                    CameraPosition(
                        LatLng(
                            tencentGeoLocation?.location?.latitude!!, tencentGeoLocation?.location?.longitude!!
                        ),  //中心点坐标，地图目标经纬度
                        16f,  //目标缩放级别
                        0f,  //目标倾斜角[0.0 ~ 45.0] (垂直地图时为0)
                        0f
                    )
                ) //目标旋转角 0~360° (正北方为0)
                tencentMap?.moveCamera(cameraSigma) //移动地图
                gps++
            }
            val custom = BitmapDescriptorFactory.fromResource(R.mipmap.bus_1)

            mCustomMarker = tencentMap?.addMarker(
                MarkerOptions(
                    LatLng(
                        tencentGeoLocation.location.latitude, tencentGeoLocation.location.longitude
                    )
                ).icon(custom).alpha(0.7f).flat(false).clockwise(true)
            )
            //平滑移动
            val translateAnimation = TranslateAnimation(
                LatLng(
                    tencentGeoLocation.location.latitude, tencentGeoLocation.location.longitude
                )
            )
            translateAnimation.duration = 1000
            translateAnimation.interpolator = AccelerateDecelerateInterpolator()
            mCustomMarker?.setAnimation(translateAnimation)

            siteLongitude = tencentGeoLocation.location.longitude
            siteLatitude = tencentGeoLocation.location.latitude


            viewModel.saveTransitPositionInfo(
                tencentGeoLocation.location.latitude.toString(), tencentGeoLocation.location.longitude.toString()
            )
//            LiveEventBus.get<TencentGeoLocation>("tencentGeoLocation").post(tencentGeoLocation)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //解除任务
        mQueryTransitOrderDisposable.dispose()
        mQueryTransitNotificationDisposable.dispose()

        layerRootDrive?.onDestroy()
        navigatorDrive.stopNavigation()

        // 移除导航监听
        navigatorDrive.unregisterObserver(mCarNavigatorDriveObserver)
        locationApi?.removeLocationObserver(locationObserver)


        // 移除默认面板
        layerRootDrive?.removeViewLayer(layerViewDrive)


        // 解绑导航地图
        if (layerRootDrive != null) {
            navigatorDrive.unbindView(layerRootDrive)
        }
        val ttsPlayer = navigatorDrive.ttsPlayer
        if (ttsPlayer != null && ttsPlayer is TTSPlayer) {
            (ttsPlayer as TTSPlayer).stop()
        }

        // 移除默认面板
//        layerRootDrive!!.removeViewLayer(layerViewDrive)
        // 解绑导航地图
//        navigatorDrive!!.unbindView(layerRootDrive)
        // 关闭TTS和导航
//
    }


    inner class MapPopAdapter : BaseQuickAdapter<BQueryDriverTransitOrderListBean, BaseViewHolder>, BaseQuickAdapter.OnItemClickListener {
        constructor() : super(R.layout.mappopitem, null) {
            onItemClickListener = this
        }

        @SuppressLint("ResourceType")
        override fun convert(helper: BaseViewHolder?, item: BQueryDriverTransitOrderListBean?) {
            helper?.setText(R.id.popRecyCode, item?.mobileLastFour)
            helper?.setText(R.id.popRecyoriginAddress, item?.originAddress)
            helper?.setText(R.id.popRecydestinationAddress, item?.destinationAddress)
            when (item?.orderStatus) {
                1 -> {
                    helper?.setText(R.id.popRecyorderStatus, "待支付")
                }

                2 -> {
                    helper?.setText(R.id.popRecyorderStatus, "待呼叫")
                }

                3 -> {
                    helper?.setText(R.id.popRecyorderStatus, "呼叫中")
                }

                4 -> {
                    helper?.setText(R.id.popRecyorderStatus, "未上车")
                    val drawable = GradientDrawable()
                    drawable.shape = GradientDrawable.RECTANGLE
                    drawable.gradientType = GradientDrawable.RECTANGLE
                    drawable.cornerRadius = 10f
                    drawable.setColor(resources.getColor(R.color.colorRed))
                    helper?.itemView?.popRecyLly?.background = drawable
                    helper?.setTextColor(R.id.popRecyCode, getColor(R.color.white))
                    helper?.setTextColor(R.id.popRecyoriginAddress, getColor(R.color.white))
                    helper?.setTextColor(R.id.popRecydestinationAddress, getColor(R.color.white))
                    helper?.setTextColor(R.id.popRecyorderStatus, getColor(R.color.white))
                    helper?.setTextColor(R.id.popRecyverify, getColor(R.color.white))
                }

                5 -> {
                    helper?.setText(R.id.popRecyorderStatus, "未上车")
                    val drawable = GradientDrawable()
                    drawable.shape = GradientDrawable.RECTANGLE
                    drawable.gradientType = GradientDrawable.RECTANGLE
                    drawable.cornerRadius = 10f
                    drawable.setColor(resources.getColor(R.color.colorRed))
                    helper?.itemView?.popRecyLly?.background = drawable
                    helper?.setTextColor(R.id.popRecyCode, getColor(R.color.white))
                    helper?.setTextColor(R.id.popRecyoriginAddress, getColor(R.color.white))
                    helper?.setTextColor(R.id.popRecydestinationAddress, getColor(R.color.white))
                    helper?.setTextColor(R.id.popRecyorderStatus, getColor(R.color.white))
                    helper?.setTextColor(R.id.popRecyverify, getColor(R.color.white))

                }

                6 -> {
                    helper?.setText(R.id.popRecyorderStatus, "已上车")
                    val drawable = GradientDrawable()
                    drawable.shape = GradientDrawable.RECTANGLE
                    drawable.gradientType = GradientDrawable.RECTANGLE
                    drawable.cornerRadius = 10f
                    drawable.setColor(resources.getColor(R.color.green3))
                    helper?.itemView?.popRecyLly?.background = drawable
                    helper?.setTextColor(R.id.popRecyCode, getColor(R.color.white))
                    helper?.setTextColor(R.id.popRecyoriginAddress, getColor(R.color.white))
                    helper?.setTextColor(R.id.popRecydestinationAddress, getColor(R.color.white))
                    helper?.setTextColor(R.id.popRecyorderStatus, getColor(R.color.white))
                    helper?.setTextColor(R.id.popRecyverify, getColor(R.color.white))
                }

                7 -> {
                    helper?.setText(R.id.popRecyorderStatus, "行程结束")
                }

                8 -> {
                    helper?.setText(R.id.popRecyorderStatus, "已取消")
                }

                9 -> {
                    helper?.setText(R.id.popRecyorderStatus, "已退款")
                }
            }

        }

        override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View?, position: Int) {
//            view?.findViewById<LinearLayout>(R.id.popRecyLly)?.setBackgroundColor(getColor(R.color.green3))
//            view?.findViewById<TextView>(R.id.popRecyCode)?.setTextColor(getColor(R.color.white))
//            view?.findViewById<TextView>(R.id.popRecyoriginAddress)?.setTextColor(getColor(R.color.white))
//            view?.findViewById<TextView>(R.id.popRecydestinationAddress)?.setTextColor(getColor(R.color.white))
//            view?.findViewById<TextView>(R.id.popRecyorderStatus)?.setTextColor(getColor(R.color.white))
//            view?.findViewById<TextView>(R.id.popRecyverify)?.setTextColor(getColor(R.color.white))
            showLoading()
            val item = adapter.getItem(position) as BQueryDriverTransitOrderListBean
            //确认当点订单
            viewModel.getOnTransit(item.orderId, viewModel.queryPassengerBySite.value?.siteId?.toInt()!!, siteLatitude.toString(), siteLongitude.toString())
        }
    }


    inner class NextAdapter : BaseQuickAdapter<QueryTransitRouteBean, BaseViewHolder> {
        constructor() : super(R.layout.item_next_map, null) {

        }

        @SuppressLint("ResourceType")
        override fun convert(helper: BaseViewHolder, item: QueryTransitRouteBean) {
            helper.setText(R.id.tvNextDot1, item.siteName)
        }

    }


    //dialog
    @SuppressLint("MissingInflatedId")
    fun DialogOrder() {
//        if (mPopwindow != null) {
//            mPopwindow?.dismiss()
//        }
//        DialogMessage(this).setMessageTitle("提示").setContext("您有新的订单,请立即查看!").show()
        navigatorDrive.ttsPlayer.broadcast(NavTTSInfo(NavTTSInfo.BeepType.None.asValue(), "有乘客新订单"))
    }

    inner class CarNavigatorDriveObserver : NavigatorDriveObserver {
        override fun onDidStartNavigation() {

        }

        override fun onDidStopNavigation() {//结束导航
            MLog.d("结束导航--->  onDidStopNavigation   ")
//            stopNavigationMap()
            //语音提示
            showTTsNextDot()
        }

        override fun onWillArriveDestination() {
            MLog.d("到达目的地附近停止导航")
//            navigatorDrive.stopNavigation()
//            layerRootDrive?.onPause()

        }

        override fun onNavDataInfoUpdate(p0: NavDriveDataInfo?) {

        }

        override fun onNavLocationInfoUpdate(p0: NavLocationInfo?) {

        }

        override fun onStartRerouting(p0: Int) {

        }

        override fun onRouteRequestDidSucceed(p0: NavDriveRoutePlan?) {

        }

        override fun onRerouteDidSucceed(p0: Int, p1: NavDriveRoutePlan?) {

        }

        override fun onRerouteDidFail(p0: Int, p1: NavError?) {

        }

        override fun onPlayTTS(p0: NavTTSInfo?) {

        }

        override fun onGPSStatusChanged(p0: NavGpsStatusInfo?) {

        }

        override fun onTtsModeChange(p0: NavTTSMode?) {

        }

        override fun onDayNightStatusChange(p0: NavDayNightStatus?) {

        }

        override fun onShowEnlargedMap(p0: NavEnlargedMapInfo) {
            MLog.d("----->   " + Gson().toJson(p0))
        }

        override fun onHideEnlargedMap() {

        }

        override fun onWillShowLaneGuide(p0: NavLaneInfo?) {

        }

        override fun onArriveWaypoint(p0: NavWaypoint?) {

        }

        override fun onHideLaneGuide() {

        }

        override fun onUpdateParallelRoad(p0: NavParallelRoadStatus?) {

        }

        override fun onEnterIdleSection(p0: NavIdleSectionInfo?) {

        }

        override fun onMainRouteDidChange(p0: String?, p1: Int) {

        }

        override fun onRecommendRouteInfo(p0: NavRecommendRouteInfo?) {

        }

        override fun onAddAlternativeRoutes(p0: MutableList<NavDriveRoute>?) {

        }

        override fun onDeleteAlternativeRoutes(p0: MutableList<String>?) {

        }

        override fun onUpdateRouteTraffic(p0: MutableList<NavDriveRouteData>?) {

        }

        override fun onRerouteDidInFence(p0: Int) {

        }

        override fun onTollStationInfoUpdate(p0: NavTollStationInfo?) {

        }

        override fun onTrafficJamInfoUpdate(p0: NavTrafficJamInfo?) {

        }

        override fun onCameraInfoUpdate(p0: MutableList<NavCameraInfo>?) {

        }
    }

    /**
     * 播报下一站语音提示
     */
    private fun showTTsNextDot() {
        mNextAdapter.data.also {
            if (it.isNotEmpty()) {
                //取下一站第一个地点播报
                navigatorDrive.ttsPlayer.broadcast(NavTTSInfo(NavTTSInfo.BeepType.None.asValue(), "即将停靠的站点${it.get(0).siteName}"))
            }
        }

    }


}


